package cluster

import (
	"fmt"
	"strconv"
	"strings"
)

const (
	KeySep = ":"

	SectionConfig   = "config"
	SectionInstance = "instance"
	SectionPayload  = "payload"
)

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func GenKey(args ...interface{}) (key string) {
	var f string
	length := len(args)
	for i := 0; i < length; i++ {
		if i != length-1 {
			f += "%v"
			f += KeySep
		} else {
			f += "%v"
		}
	}
	key = fmt.Sprintf(f, args...)
	return
}

func ParseKey(key string) (etcdRoot string, section string, serviceName string, serviceID int, err error) {
	var strServiceID string
	etcdRoot, section, serviceName, strServiceID, err = ParseKeyS(key)
	if err != nil {
		return
	}
	if strServiceID != "" {
		if strServiceID != GlobalConfigName {
			serviceID, err = strconv.Atoi(strServiceID)
			if err != nil {
				err = fmt.Errorf("ParseKey fail, %v", err)
				return
			}
		}
	}
	return
}

func ParseKeyS(key string) (etcdRoot string, section string, serviceName string, strServiceID string, err error) {
	parts := strings.Split(key, KeySep)
	length := len(parts)
	if length >= 4 {
		etcdRoot = parts[0]
		section = parts[1]
		serviceName = parts[2]
		strServiceID = parts[3]
	} else if length >= 3 {
		etcdRoot = parts[0]
		section = parts[1]
		serviceName = parts[2]
	} else if length >= 2 {
		etcdRoot = parts[0]
		section = parts[1]
	} else {
		err = fmt.Errorf("ParseKeyS fail, parts not enough")
	}
	return
}
